Home:ALL Converter>when and how is memory separate in c++ multithreading?

when and how is memory separate in c++ multithreading?

Ask Time:2021-11-12T02:06:09         Author:Timangar

Json Formatter

In multithreading (with std::thread for example), the process memory is shared between threads. However, does this extend to a function being called with two different arguments?

A silly example:

int add_two_in_ridiculous_fashion(int x) {
    x++;
    std::this_thread::sleep(1s);
    x++;
    return x;
}

While the thread is sleeping, another thread rolls in and replaces x with a different value, and the two threads return the latter's value + 1 and + 2 respectively. Is this possible?

If yes, is there a lock-free approach of preventing this in C++?

Author:Timangar,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69932926/when-and-how-is-memory-separate-in-c-multithreading
PMF :

No, this is not going to cause any problems. Each thread gets its own stack, and local variables and arguments (the x in your case) are on the stack and therefore separate for each thread. Member variables of a class or global variables are shared across different threads (for the same object instance).",
2021-11-11T18:09:34
yy